package com.htjx.mall.services;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.htjx.mall.admin.controllers.vo.UserQuery;
import com.htjx.mall.commons.mappers.AccountMapper;
import com.htjx.mall.commons.mappers.TicketMapper;
import com.htjx.mall.commons.mappers.UserMapper;
import com.htjx.mall.commons.models.User;
import com.htjx.mall.commons.models.enums.SeqType;
import com.htjx.mall.commons.models.user.Account;
import com.htjx.mall.commons.utils.page.Page;

@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private SequenceManager sequenceManager;
	@Autowired
	private TransactionTemplate transactionTemplate;
	
	@Autowired
	private TicketMapper ticketMapper;
	@Autowired
	private AccountMapper accountMapper;
	
	public void insertOne(final User user) {
		long[] seq = sequenceManager.buildBatchSeq(SeqType.User, 1);
		user.setId(seq[0]);
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				userMapper.insertOne(user);
				//presentTickets(user, new BigDecimal(5), 20);
				createAccount(user);
			}
		});
	}
	
//	/****
//	 * 活动1： 新用户注册，获赠100元现金抵用券（20 x 5元）
//	 * @param user
//	 */
//	private void presentTickets(User user, BigDecimal amount, int number) {
//		long[] seq = sequenceManager.buildBatchSeq(SeqType.Ticket, 20);
//		List<Ticket> ticketList = new ArrayList<Ticket>();
//		Date date = Dates.getTheDayMidnight(Dates.nextYear(new Date()));
//		for(int i = 0; i < number; i++) {
//			Ticket ticket = new Ticket();
//			ticket.setId(seq[i]);
//			ticket.setAmount(amount);
//			ticket.setDeadline(date);
//			ticket.setUsed(false);
//			ticket.setUser_id(user.getId());
//			ticketList.add(ticket);
//		}
//		ticketMapper.insertBatch(ticketList);
//	}
	
	private void createAccount(User user) {
		long[] seq = sequenceManager.buildBatchSeq(SeqType.Account, 1);
		Account account = new Account();
		account.setId(seq[0]);
		account.setUser_id(user.getId());
		account.setCash(BigDecimal.ZERO);
		account.setFrozen_cash(BigDecimal.ZERO);
		account.setTotal_recharge(BigDecimal.ZERO);
		/**
		 * 新用户注册赠送100个麦豆
		 * 20141002 取消送麦豆
		 * **/
		account.setGold_coin(0);
		account.setFrozen_gold_coin(0);
		account.setPoints(0);
		account.setFrozen_points(0);
		accountMapper.insertOne(account);
	}
	
	
	public void updateOne(final User user) {
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				userMapper.updateOne(user);
			}
		});
	}
	
	/**
	 * 检测唯一属性
	 */
	public boolean checkUniqueByProperty(String propertyName, String propertyValue) {
		return !userMapper.selectByProperty(propertyName, propertyValue).isEmpty();
	}
	
	public User findUniqueBy(String propertyName, String propertyValue) {
		List<User> list = userMapper.selectByProperty(propertyName, propertyValue);
		if (list.isEmpty()) {
			return null;
		}
		if (list.size() == 1) {
			return list.get(0);
		}
		throw new RuntimeException("there are too many rows, actual " + list.size());
	}
	
//	public Wallet selectWallet(User user, Date date) {
//		return userMapper.selectWallet(user.getId(), date);
//	}
	
	public Page<User> page(UserQuery userQuery, Page<User> page) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("offset", page.getFirst() - 1);
		params.put("size", page.getPageSize());
		params.put("userQuery", userQuery);
		List<User> result = userMapper.page(params);
		page.setResult(result);
		if (page.isAutoCount()) {
			int totalCount = userMapper.pageCount(params);
			page.setTotalCount(totalCount);
		}
		
		return page;
	}
}
